package com.nash.demands;

import java.util.HashMap;
import java.util.Map;
import org.ksoap2.serialization.SoapObject;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import android.provider.Settings.Secure;

public class UpdateThread extends Thread {
  Handler mHandler;

  public Map<String, Integer> aSeverVersions;

  final static int STATE_DONE = 0;
  final static int STATE_RUNNING = 1;
  final String f1[][] = { { BaseColumns._ID, Helper.TBL_HOST_NAME, Helper.TBL_HOST_IS_ARC }, { BaseColumns._ID, Helper.TBL_OSNR_NAME, Helper.TBL_OSNR_IS_ARC },
      { BaseColumns._ID, Helper.TBL_ANSWER_NAME, Helper.TBL_ANSWER_IS_ARC },
      { BaseColumns._ID, Helper.TBL_GOODS_NAME, Helper.TBL_GOODS_ID_PARENT, Helper.TBL_GOODS_CODE, Helper.TBL_GOODS_TREE_STR, Helper.TBL_GOODS_IS_ARC },
      { BaseColumns._ID, Helper.TBL_AGENT_NAME, Helper.TBL_AGENT_ADDRESS, Helper.TBL_AGENT_PHONE, Helper.TBL_AGENT_ID_ANSWER, Helper.TBL_AGENT_IS_ARC },
      { BaseColumns._ID, Helper.TBL_TU_ID_GOODS, Helper.TBL_TU_NAME, Helper.TBL_TU_INBOX, Helper.TBL_TU_PRICE, Helper.TBL_TU_NOMER, Helper.TBL_TU_CATALOG, Helper.TBL_TU_IS_ARC }, { BaseColumns._ID, Helper.TBL_TU_STOCK } };
  final String f2[][] = { { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c" }, { "a", "b", "c", "d", "e", "f" }, { "a", "b", "c", "d", "e", "f" }, { "a", "b", "c", "d", "e", "f", "g", "h" }, { "a", "b" } };
  final public String[] vers = { "host", "osnr", "answer", "goods", "agent", "tu_main", "tu_ostatok" };
  final public String[] soap = { "getHost", "getOsnr", "getAnswers", "getGoods", "getAgents", "getTuMain", "getTuOstatok" };

  final public String[] tables = { Helper.TBL_HOST, Helper.TBL_OSNR, Helper.TBL_ANSWER, Helper.TBL_GOODS, Helper.TBL_AGENT, Helper.TBL_TU, Helper.TBL_TU };
  final public static String VER_GOODS = "goods";
  final public static String VER_TU_MAIN = "tu_main";
  final public static String VER_TU_OSTATOK = "tu_ostatok";
  final public static String VER_ANSWER = "answer";
  final public static String VER_HOST = "host";
  final public static String VER_OSNR = "osnr";
  final public static String VER_AGENT = "agent";

  int mState;
  DemandsActivity app;

  UpdateThread(Handler h, DemandsActivity act) {
    mHandler = h;
    app = act;
  }

  public void run() {
    mState = STATE_RUNNING;
    Message msg;
    try {
      aSeverVersions = getAllServerVersions(mHandler);
      for (int i = 0; i < vers.length; i++) {
        String verItem = vers[i];
        if (mustUpdate(verItem)) {
          updateTable(soap[i], verItem, f1[i], f2[i], tables[i], i + 2, mHandler);
        }
      }

      msg = mHandler.obtainMessage();
      msg.arg1 = -1;
      msg.arg2 = DemandsActivity.UPDATE_STAGE_FINISH;
      mHandler.sendMessage(msg);
    } catch (DemandsException e2) {
      if (e2.getCode()==DemandsException.SOAP_FAULT){
        msg = mHandler.obtainMessage();
        msg.arg1 = -1;
        msg.arg2 = DemandsActivity.UPDATE_ERROR;
        app.code2=e2.getCode2();
        
        mHandler.sendMessage(msg);
      }
    }
  }

  public void setState(int state) {
    mState = state;
  }

  public void updateTable(final String method_name, final String ver_name, String fieldTable[], String fieldSoap[], String table, int stage, Handler h) throws DemandsException {
    Message msg = h.obtainMessage();
    msg.arg1 = -1;
    msg.arg2 = stage;
    h.sendMessage(msg);
    SoapObject res = app.transport.LoadBySoap(method_name, getVersion(ver_name), 
        Secure.getString(app.getContentResolver(), Secure.ANDROID_ID), app.getLicenseId(), app.getUserId(),null);
    
    
    int cnt = res.getPropertyCount();
    msg = h.obtainMessage();
    int stagecnt=stage*100000+cnt;
    msg.arg1 = 0;
    msg.arg2 = stagecnt;
    h.sendMessage(msg);

    int step = Math.round(cnt / 300);
    try {
      for (int i = 0; i < cnt; i++) {
        SoapObject o = (SoapObject) res.getProperty(i);
        ContentValues cv = new ContentValues();
        for (int k = 0; k < fieldTable.length; k++) {
          cv.put(fieldTable[k], o.getProperty(fieldSoap[k]).toString());
        }
        if (method_name.equals("getTuOstatok"))
          DemandsActivity.db.update(table, cv, "_id=?", new String[] { o.getProperty("a").toString() });
        else
          DemandsActivity.db.replace(table, null, cv);
        /*
         * StringBuilder sb=new StringBuilder();
         * sb.append("update tu set stock="); sb.append( (o.getProperty("b")) );
         * sb.append(" where _id="); sb.append(o.getProperty("a"));
         * DemandsActivity.db.execSQL(sb.toString());
         */

        if (h != null && ((step != 0 && i % step == 0) || step== 0)) {
          msg = h.obtainMessage();
          msg.arg1 = i+1;
          msg.arg2 = stagecnt;
          h.sendMessage(msg);
        }

      }
    } catch (Exception e) {
      throw new DemandsException(e);
    }
    setVersion(ver_name, aSeverVersions.get(ver_name));
  }

  public boolean mustUpdate(String table) {
    return (aSeverVersions.get(table) > getVersion(table));
  }

  public void setVersion(String s, int v) {
    ContentValues cv = new ContentValues();
    cv.put(Helper.TBL_VERSIONS_NAME, s);
    cv.put(Helper.TBL_VERSIONS_VALUE, v);
    DemandsActivity.db.replace(Helper.TBL_VERSIONS, null, cv);
  }

  public Map<String, Integer> getAllServerVersions(Handler hndl) throws DemandsException {

    Message msg = hndl.obtainMessage();
    msg.arg1 = 0;
    msg.arg2 = DemandsActivity.UPDATE_STAGE_GET_VERSIONS;
    hndl.sendMessage(msg);

    SoapObject res = app.transport.LoadBySoap("getAllVersions", 0, 
        Secure.getString(app.getContentResolver(), Secure.ANDROID_ID), app.getLicenseId(), app.getUserId(),null);

    Map<String, Integer> v = new HashMap<String, Integer>();
    for (int i = 0, j = res.getPropertyCount(); i < j; i++) {
      SoapObject o = (SoapObject) res.getProperty(i);
      v.put(o.getProperty("table").toString(), Integer.valueOf(o.getProperty("version").toString()));
    }
    return v;
  }

  public int getVersion(String s) {
    StringBuilder sb = new StringBuilder().append("select " + Helper.TBL_VERSIONS_VALUE + " from " + Helper.TBL_VERSIONS + " where " + Helper.TBL_VERSIONS_NAME + "='").append(s).append("'");
    Cursor data = DemandsActivity.db.rawQuery(sb.toString(), null);
    int version = 0;
    if (data.moveToFirst()) {
      do {
        version = data.getInt(0);
      } while (data.moveToNext());
    }
    if (!data.isClosed())
      data.close();
    return version;
  }

  
}
